package org.github.choviwu.example.common.util;

import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * Created by ChoviWu on 2018/03/18
 * Description: 文件下载Util
 */
public class DownLoadUtils {

    /**
     * 文件下载工具类
     * @param filePath  文件路径
     * @param response  响应体
     * @return
     */
    public static void downLoad(String filePath,HttpServletResponse response){
        File file = new File(filePath);
        byte[] buff =new byte[2048];
        int index=0;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            while ((index=inputStream.read(buff))!=-1){
                outputStream.write(buff,0,index);
                outputStream.flush();
            }
            IOUtils.copy(inputStream,outputStream);
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
}
    /**
     * 文件下载工具类
     * @param filePath  文件路径
     * @param dirPath   服务器文件夹路径
     * @return
     */
    public static String downLoad(String filePath,String dirPath){
        File file = new File(filePath);
        byte[] buff =new byte[2048];
        int index=0;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String fileName = DateUtil.getDate("yyyyMMdd")+ new Date().getTime() + ".jpg" ;
        try {
            inputStream = new FileInputStream(file);

            outputStream = new FileOutputStream(new File(dirPath+fileName));
            while ((index=inputStream.read(buff))!=-1){
                outputStream.write(buff,0,index);
                outputStream.flush();
            }
            IOUtils.copy(inputStream,outputStream);
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return fileName;
    }
}
